<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    :title="getTitle"
    @ok="handleOK"
  >
    <div>
      <BasicForm @register="chatregisterForm"> </BasicForm>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { chatAccountFormSchema } from './account.data';
  import { createTaskChat } from '@/api/demo/chat';
  import { message } from 'ant-design-vue';
  import { getdeviceToOwnerAPI } from '@/api/demo/videoList';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  defineOptions({ name: 'AccountModal' });

  const userNoList = ref<string[]>([]);
  const modalWidth = ref('30%');
  const isUpdate = ref(true);
  const rowId = ref('');
  const deviceList = ref<any[]>([]);
  const emit = defineEmits(['success']);

  // 方法定义
  const [chatregisterForm, { getFieldsValue }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: chatAccountFormSchema,
    showActionButtonGroup: false,
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    userNoList.value = data.userNoList;
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('sys.configuration.add') : t('sys.configuration.edit')));

  async function handleOK() {
    if (!userNoList.value) {
      return '请选选择人员';
    }

    const deviceLabels = getFieldsValue()
      .devices.map((deviceId) => {
        const device = deviceList.value.find((d) => d.value === deviceId);
        return device ? device.label : '';
      })
      .filter((label) => label !== ''); // 过滤掉空字符串
    const devicesString = deviceLabels.join(', '); // 将设备标签用逗号拼接起来

    const Data = {
      ...getFieldsValue(),
      userNos: userNoList.value,
      devices: devicesString,
    };
    try {
      const data = await createTaskChat(Data);
      emit('success', data);
      closeModal();
      message.success(t('sys.configuration.succesSubmit'));
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  onMounted(async () => {
    try {
      // 获取设备管理
      const deviceresponse = await getdeviceToOwnerAPI();
      deviceList.value = deviceresponse.data; // 假设接口返回的数据结构为 { data: [] }
    } catch (error) {
      console.error('获取模板列表失败', error);
    }
  });
</script>
